/**
 * @file
 *           base64.h
 * @brief
 *          <fillin>purpose
 *
 * @par Author (last changes):
 *          - Herea Adrian
 *          
 * @par Description:
 *
 *
 * @par Module-History:
 * @verbatim
 *  Date        Author				Reason
 *  15.01.2010  Herea Adrian         Initial creation
 *
 * @endverbatim
 *
 * @par Copyright Notice:
 * @verbatim
 * Copyright (C) 2010
 * All Rights Reserved.
 * The reproduction, transmission or use of this document or its contents is
 * not permitted without express written authority.
 * Offenders will be liable for damages. All rights, including rights created
 * by patent grant or registration of a utility model or design, are reserved.
 **/
#include "StdAfx.h"
#include "SocketServer.h"

//#include <iostream>

SocketServer::SocketServer(SOCKET winSocketServer) :
  AbstractSocket(INVALID_SOCKET), m_winSocketServer(winSocketServer)
{
}

SocketServer*
SocketServer::init(string ipAddress, int port)
{
  SocketServer* server = NULL;
  SOCKET winSocketServer = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);

  if (winSocketServer == INVALID_SOCKET)
    {
      return NULL;
    }

  struct sockaddr_in local;
  memset(&local, 0, sizeof(local));
  local.sin_family = AF_INET;
  local.sin_addr.s_addr = inet_addr(ipAddress.c_str());
  local.sin_port = htons(port);

  if (bind(winSocketServer, (SOCKADDR*) &local, sizeof(local)) == SOCKET_ERROR)
    {
      closesocket(winSocketServer);
      return NULL;
    }

  if (listen(winSocketServer, 1) == SOCKET_ERROR)
    {
      closesocket(winSocketServer);
      return NULL;
    }

  server = new SocketServer(winSocketServer);

  printf("\nServer on %s : %d \n", ipAddress.c_str(), port);
  return server;
}

void
SocketServer::run()
{
  while (TRUE)
    {
      m_winSocket = accept(m_winSocketServer, NULL, NULL);
      if (m_winSocketServer != INVALID_SOCKET)
        {
          printf("Accepted client connection...\n");
          socketListen();
          closesocket( m_winSocket);
          m_winSocket = INVALID_SOCKET;
        }
    }
}

SocketServer::~SocketServer(void)
{
  if (m_winSocketServer != INVALID_SOCKET)
    {
      closesocket( m_winSocketServer);
    }
}
